#pragma once
#include<iostream>
using namespace std;

template<class K>
class BSTreeNode
{
public:
	BSTreeNode* _left;
	BSTreeNode* _right;
	K _val;
	BSTreeNode(const K& val)
		:_left(nullptr)
		,_right(nullptr)
		,_val(val)
	{ }

};
template<class K>
class BSTree
{
	typedef BSTreeNode<K> Node;
public:
	BSTree()
		:_root(nullptr)
	{ }

	bool Insert(K key)
	{
		if (_root == nullptr)
		{
			_root = new Node(key);
			return true;
		}

		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (key < cur->_val)
			{
				parent = cur;
				cur = cur->_left;
			}
			else if (key > cur->_val)
			{
				parent = cur;
				cur = cur->_right;
				//directions = dir_right;
			}
			else
			{
				return false;
			}
		}
			cur = new Node(key);

			
			if (parent->_val < key)
			{
				parent->_right = cur;
			}
			else
			{
				parent->_left = cur;
			}

			return true;
		
	}

	void Inorder()
	{
		_Inorder(_root);
	}

	void _Inorder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		_Inorder(root->_left);
		cout << root->_val << " ";
		_Inorder(root->_right);
		//cout << endl;

	}

	bool Find(const K& val)
	{
		Node* cur = _root;
		while(cur)
		{
			if (cur->_val > val)
			{
				cur = cur->_left;
			}
			else if (cur->_val < val)
			{
				cur = cur->_right;
			}
			else
			{
				return true;
			}
		}
		return false;
	}

	bool Erase(const K & val)
	{
		Node* cur = _root;
		Node* parent = nullptr;
		while (cur)
		{
			if (cur->_val < val)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_val > val)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				if (cur->_left == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_right;
					}
					else
					{
						if (parent->_left == cur)
						{
							parent->_left = cur->_right;
						}
						else
						{
							parent->_right = cur->_right;
						}
					}
				
				}

				else if (cur->_right == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_left;
					}

					else
					{
						if (parent->_left == cur)
						{
							parent->_left = cur->_left;
						}
						else if (parent->_right == cur)
						{
							parent->_right = cur->_left;
						}
					}
					
				}
				else
				{
					Node* parent = cur;
					Node* leftMax = cur->_left;

					while (leftMax->_right)
					{
						parent = leftMax;
						leftMax = leftMax->_right;
					}

					swap(cur->_val, leftMax->_val);
					if (parent->_left == leftMax)
					{
						parent->_left = leftMax->_left;
					}
					else
					{
						parent->_right = leftMax->_left;
					}

					cur = leftMax;
				}
				delete cur;
				return true;
			}
		}
		return false;
	}

private:

	Node* _root;
};

void test()
{
	int a[] = { 8,3,1,10,6,4,7,14,13 };
	BSTree<int> t;
	for (auto i : a)
	{
		t.Insert(i);
	}
	t.Inorder();
	cout << endl;

	//cout<<t.Find(1);
	t.Erase(1);
	cout << endl;

	t.Inorder();
	cout << endl;
	for (auto i : a)
	{
		t.Erase(i);
	}

}